#include "EmailIPUpdate.h"

#include "poco/Net/MailMessage.h"
#include "poco/Net/MailRecipient.h"
#include "poco/Net/SMTPClientSession.h"
#include "poco/Net/POP3ClientSession.h"
#include "poco/Exception.h"

#include <string>
#include <stdexcept>

using Poco::Net::MailMessage;
using Poco::Net::MailRecipient;
using Poco::Net::SMTPClientSession;
using Poco::Net::POP3ClientSession;
using Poco::Exception;

using std::string;

EmailIPUpdate::EmailIPUpdate(const string& emailAddress, const string& password)
:m_EmailAddress(emailAddress),m_Password(password)
{
	string::size_type atLocation = m_EmailAddress.find('@');
	if(atLocation == string::npos)
	{
		throw std::invalid_argument("The emailAddress is invalid");
	}

	m_Username = m_EmailAddress.substr( 0, atLocation);

	string domainName = m_EmailAddress.substr(atLocation + 1);
	m_PopAddress = "pop." + domainName;
	m_SmtpAddress = "smtp." + domainName;

}

EmailIPUpdate::EmailIPUpdate(const string& emailAddress,const string& username, const string& password,
							 const string& popAddress, const string& smtpAddress )
:m_EmailAddress(emailAddress), m_PopAddress(popAddress), m_SmtpAddress(smtpAddress), m_Password(password)
{
	string::size_type atLocation = m_EmailAddress.find('@');
	if(atLocation == string::npos)
	{
		throw std::invalid_argument("The emailAddress is invalid");
	}
	m_Username = m_EmailAddress.substr( 0, atLocation);
}

void EmailIPUpdate::updateIP(const std::string &newIP)
{
	try{
		MailMessage ipMessage;

		ipMessage.setSubject("IP"+ newIP);
		ipMessage.setSender(m_EmailAddress);
		ipMessage.setContent(newIP);
		ipMessage.addRecipient( MailRecipient(MailRecipient::PRIMARY_RECIPIENT, m_EmailAddress) );

		SMTPClientSession smtpSession(m_SmtpAddress);
		smtpSession.login(SMTPClientSession::AUTH_LOGIN, m_Username, m_Password);
		smtpSession.sendMessage(ipMessage);

	}catch(const Exception& e)
	{
		throw std::runtime_error(e.displayText());
	}
}

string EmailIPUpdate::getIP() const
{
	try{
		MailMessage mailMessage;

		POP3ClientSession popSession(m_PopAddress);
		popSession.login(m_Username, m_Password);
		
		POP3ClientSession::MessageInfoVec messageInfoVec;
		popSession.listMessages(messageInfoVec);
		for (POP3ClientSession::MessageInfoVec::reverse_iterator it = messageInfoVec.rbegin(); 
			it != messageInfoVec.rend() ; it++)
		{
			popSession.retrieveMessage(it->id, mailMessage);
			if(mailMessage.getSubject().substr(0,2) == "IP")
			{
				string ip = mailMessage.getSubject().substr(2);
				return ip;
			}
		}
		throw std::runtime_error("Can't get ip from the email address");
	}catch(const Exception& e)
	{
		throw std::runtime_error(e.displayText());
	}
}